package reflect;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 动态代理
 * @Auther Jun jie Yi
 * @Date 21:18 2022/1/9
 */


interface PersonInterface {

    public void buy(String b);

    public void buy1(String b1);
}

class Person implements PersonInterface {

    private String name;
    private String house;

    public Person(String name, String house) {
        this.name = name;
        this.house = house;
    }

    @Override
    public void buy(String b) {
        System.out.println("buy:" + b);
    }

    @Override
    public void buy1(String b1) {
        System.out.println("buy1:" + b1);
    }

    @Override
    public String toString() {
        return "Person [house=" + house + ", name=" + name + "]";
    }
}

class ProxySale implements InvocationHandler {

    public PersonInterface personInterface;

    public PersonInterface newInstall(PersonInterface personInterface) {
        //注意这里接受的是 new Person("yijunjie", "house")
        //这里存在一个向上转型  Person -> PersonInterface
        this.personInterface = personInterface;
        // 将Person 对象的 ClassLoader Interfaces 继承了InvocationHandler接口的对象
        return (PersonInterface) Proxy.newProxyInstance(this.getClass()
                .getClassLoader(), personInterface.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("执行方法前的操作");
        //执行类中的方法()
        method.invoke(personInterface, args);
        System.out.println("执行方法后的操作");
        return null;
    }
}

public class ProxyDemo {
    public static void main(String[] args) {
        ProxySale ProxySale = new ProxySale();
        //这里的  t 相当于new Person("yijunjie", "house")的一个加强对象
        PersonInterface t = ProxySale.newInstall(new Person("yijunjie", "house"));
        t.buy("aaaa");
    }
}
